import {AfterViewInit, Component, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {MessageService, ModalComponent, paginationFactory, PaginationService, ProgressBarService, Table} from '../../../../../ng-tools';
import {HttpClient} from '@angular/common/http';
import {AllChannelService} from '../../../../services/api/all-channel.service';
import {AllChannelFormatterService} from '../../../../services/formatter/all-channel-formatter.service';
import {Message} from '../../../../../ng-tools/src/message/message';
import {Subscription} from 'rxjs';
import {Router} from '@angular/router';
import {finalize} from 'rxjs/internal/operators';
import {DvbConfigService} from '../../../../services/api/dvb-config.service';
const paginationProvider = {
  provide: PaginationService,
  useFactory: paginationFactory,
  deps: [HttpClient, AllChannelService]
};
@Component({
  selector: 'channel-manage',
  templateUrl: './channel-manage.component.html',
  styleUrls: ['./channel-manage.component.scss'],
  providers: [
    AllChannelService,
    AllChannelFormatterService,
    paginationProvider
  ]
})
export class ChannelManageComponent implements OnInit, AfterViewInit, OnDestroy, Message {
  subscriptions: Subscription;
  @ViewChild('modal') private modal: ModalComponent;
  @ViewChild('fileInput') fileInput;
  allChannel;
  channelPage;
  channelTable = new Table({
    headers: this.channelFormatter.formatter,
  });
  breadcrumb = [
    {name: '资源管理', cssIcon: 'fa fa-fw fa-cubes'},
    {name: '频道管理', cssIcon: 'fa fa-fw fa-microchip'}
  ];
  selectInfo = {
    search: {
      title: '搜索',
      name: 'name',
      placeholder: '频道名称'
    },
    choiceItems: [
      {
        title: '频率',
        name: 'freq',
        choices: [
        ],
      }
    ],
  };
  constructor(private channelFormatter: AllChannelFormatterService,
              private pagination: PaginationService,
              private router: Router,
              private dvbConfigService: DvbConfigService,
              private channelService: AllChannelService,
              private message: MessageService,
              public progress: ProgressBarService) { }

  ngOnInit() {
    this.pagination.setPageParam(1, 12);
    this.pagination.init(this.channelTable.options.headers);
    this.channelPage = this.pagination;
    this.channelService.get('').subscribe((resp) => {
      this.allChannel = resp.body;
      const freqs = [];
      for (const channel of this.allChannel) {
        if (freqs.indexOf(channel.freq) === -1) {
          freqs.push(channel.freq);
        }
      }
      for (const freq of freqs) {
        this.selectInfo.choiceItems[0].choices.push({name: String(freq), value: freq});
      }
      this.message.sendMessage('page load progress', this);
    });
    /** 绑定事件 */
    this.pagination.dataLoadSubscriber$.pipe(finalize(() => {
    })).subscribe({
      error: error => {
        console.log(error);
      }
    });
  }
  onSelected(e) {
    this.pagination.queryParams = e.forPaginationService;
    this.pagination.reload();
  }
  ngAfterViewInit(): void {
    this.message.sendMessage('breadcrumb changed', this, this.breadcrumb);
    this.message.sendMessage('page load progress', this, '300ms');
  }
  downloadFile() {
    this.dvbConfigService.get(this.dvbConfigService.urls.download_channel_file).subscribe((resp) => {
      const file = new Blob([resp.body], { type: 'text/plain'});
      const a = document.createElement('a');
      document.body.appendChild(a);
      a.download = 'channels.txt';
      a.href = URL.createObjectURL(file);
      a.click();
      a.remove();
    });
  }
  postFile() {
    this.fileInput.nativeElement.click();
  }
  selectFile(e) {
    const formData = new FormData();
    formData.append('file', e.target.files[0]);
    this.dvbConfigService.post(this.dvbConfigService.urls.post_channel_file, formData, {reportProgress: true, observe: 'events'}).subscribe((resp) => {
      this.pagination.refresh();
    }, (errors) => {});
  }
  ngOnDestroy(): void {
  }

}
